
import { useUserInfoStore } from '@/path/store/userInfo';
import { isObj, isJsonStr } from "../until"


const { miniProgram: { envVersion } } = uni.getAccountInfoSync();
const apiUrl = {
  develop:  "https://dev.yochegou.com/",
  trial: "https://dev.yochegou.com/",
  release: "https://yochegou.com/"
}[envVersion];

// const domainName = "https://dev.yochegou.com/"
// const domainName = "https://yochegou.com/"

function service(params) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${apiUrl}${params.url}`, //仅为示例，并非真实接口地址。
      data: params.data,
      method: params.method || "GET",
      header: getUpLoadHeader(params.header || {}),
    }).then((res) => {
      if (res.statusCode === 200 && res.data.code === 1) {
        resolve(res.data.data)
      } else {
        throw res
      }
    }).catch((err) => {
      uni.showToast({
        icon: "none",
        title: err?.data?.msg || "网络错误，请稍后再试"
      })
      reject(err)
    });
  })
}


/**单个文件上传 */
export function uploadFile(params, options = { showLoading: true }) {
  return new Promise((resolve, reject) => {
    options.showLoading && uni.showLoading({ title: '加载中' })
    params.url = params.url.indexOf("http") === 0 ? params.url : apiUrl + params.url
    uni.uploadFile({
      header: getUpLoadHeader(params.header || {}),
      ...params,
      success: (res) => {
        const _resData = isJsonStr(res.data) ? JSON.parse(res.data) : res.data
        if (res.statusCode !== 200 || (isObj(_resData) && _resData.code != 1 && _resData.msg)) {
          uni.showToast({ title: "上传失败", icon: "none" })
          return reject(_resData)
        }
        uni.hideLoading()
        resolve(_resData.data)
      },
      fail() {
        uni.showToast({ title: "上传失败", icon: "none" })
      }
    })
  })
}

function getUpLoadHeader(header = {}) {
  const userStore = useUserInfoStore()
  let _header = {
    token: userStore.userInfo.token,
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
    ...header
  }
  return _header
}

export default {
  imageUrl: "https://cdn.dwicoud.com/yck/",
  apiUrl,
  get: function (url, data, header = {}) {
    return service({
      url: url,
      data,
      method: "GET",
      header
    })
  },
  post: function (url, data, header = {}) {
    return service({
      url: url,
      data,
      method: "POST",
      header
    })
  },
}